package com.zc.im.common.decoder;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.zc.im.common.constant.enums.ResultEnum;
import com.zc.im.common.exception.CustomException;
import com.zc.im.common.vo.Result;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Project：im
 * Date：2022/4/18
 * Time：18:26
 * Description：自定义解码器
 *
 * @author Challen.Zhang
 * @version 1.0
 */
public class CustomerDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        if (!HttpStatus.valueOf(response.status()).is2xxSuccessful()) {
            throw new CustomException(ResultEnum.INTERNAL_SERVER_ERROR, "请求失败");
        }
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        if (JSONUtil.isJson(bodyStr)) {
            Result result = JSONUtil.toBean(bodyStr, Result.class);
            if (!result.isSuccess()) {
                throw new CustomException(ResultEnum.getInstance(result.getStatus()), "请求失败");
            }
            return JSONUtil.toBean(JSONUtil.toJsonStr(result.getData()), type, false);
        }
       throw new CustomException(ResultEnum.INTERNAL_SERVER_ERROR,"返回数据异常");
    }

}
